package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 圈子服务
 */
@Service
public class MovementsService {

    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    /**
     * 发布动态
     */
    public String saveMovements(String textContent,
                                String location,
                                String longitude,
                                String latitude,
                                MultipartFile[] multipartFile) throws IOException {
        //获取登录用户信息，校验token
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);

        //图片上传
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult uploadResult = this.picUploadService.upload(file);
            imageUrls.add(uploadResult.getName());
        }

        publish.setMedias(imageUrls);

        return this.quanZiApi.savePublish(publish);
    }

    /**
     * 查询好友动态
     */
    public PageResult queryPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(UserThreadLocal.get().getId(), page, pageSize);
    }

    /**
     * 查询推荐动态
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);
    }


    /**
     * 点赞
     */
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean bool = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }
        // 保存成功，获取点赞数
        return this.quanZiApi.queryCommentCount(publishId, 1);
    }

    /**
     * 取消点赞
     */
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!bool) {
            //取消失败
            return null;
        }
        //  获取点赞数
        return this.quanZiApi.queryCommentCount(publishId, 1);
    }

    /**
     * 喜欢
     */
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }
        // 保存成功，获取喜欢数
        return this.quanZiApi.queryCommentCount(publishId, 3);
    }

    /**
     * 取消喜欢
     */
    public Long unLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!bool) {
            return null;
        }
        // 取消成功，获取喜欢数
        return this.quanZiApi.queryCommentCount(publishId, 3);
    }

    /**
     * 查询一条动态
     */
    public Movements queryMovementsById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }
        //查询到动态数据，数据的填充
        List<Movements> movementsList = this.fillValueToMovements(Arrays.asList(publish));
        return movementsList.get(0);
    }

    /**
     * 查询来访记录
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitors = this.visitorsApi.topVisitor(user.getId(), 4);
        if (CollectionUtils.isEmpty(visitors)) {
            return Collections.emptyList();
        }

        List<VisitorsVo> result = new ArrayList<>();
        for (Visitors visitor : visitors) {
            UserInfo userInfo = userInfoService.queryUserInfoById(visitor.getVisitorUserId());
            VisitorsVo visitorsVo = new VisitorsVo();
            visitorsVo.setAge(userInfo.getAge());
            visitorsVo.setAvatar(userInfo.getLogo());
            visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
            visitorsVo.setId(userInfo.getUserId());
            visitorsVo.setNickname(userInfo.getNickName());
            visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
            visitorsVo.setFateValue(visitor.getScore().intValue());
            result.add(visitorsVo);
        }
        return result;
    }

    /**
     * 查询我的相册
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        pageResult.setItems(this.fillValueToMovements(records));
        return pageResult;
    }

    //查询动态
    private PageResult queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();

        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);

        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        List<Publish> records = pageInfo.getRecords();

        pageResult.setItems(this.fillValueToMovements(records));
        return pageResult;
    }

    private List<Movements> fillValueToMovements(List<Publish> records) {
        List<Movements> movementsList = new ArrayList<>();
        if (CollectionUtils.isEmpty(records)) {
            return movementsList;
        }
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            UserInfo userInfo = userInfoService.queryUserInfoById(movements.getUserId());
            movements.setAge(userInfo.getAge());
            movements.setAvatar(userInfo.getLogo());
            movements.setGender(userInfo.getSex().name().toLowerCase());
            movements.setNickname(userInfo.getNickName());
            movements.setTags(StringUtils.split(userInfo.getTags(), ','));
            movements.setDistance("1.2公里"); //TODO 距离
            movements.setHasLiked(1); //TODO 是否点赞（1是，0否）
            movements.setHasLoved(0); //TODO 是否喜欢（1是，0否）
            movements.setLikeCount(this.quanZiApi.queryCommentCount(record.getId().toString(), 1).intValue()); //TODO 点赞数
            movements.setCommentCount(this.quanZiApi.queryCommentCount(record.getId().toString(), 2).intValue()); //TODO 评论数
            movements.setLoveCount(this.quanZiApi.queryCommentCount(record.getId().toString(), 3).intValue()); //TODO 喜欢数

            movementsList.add(movements);
        }
        return movementsList;
    }

}
